const Generator = require('yeoman-generator')
const fs = require('fs')
const _ = require('lodash')
let ejs = require('ejs')
let path = require('path')

module.exports = class extends Generator {
  constructor(args, option) {
    super(args, option)
    // 暴露lodash
    this._ = _
    this._templatePath = this.templatePath('')
    this._distPath = this.destinationPath('')
  }

  copyTpl(filePath, destinationPath, args) {
    filePath = filePath || this._templatePath
    destinationPath = destinationPath || this._distPath
    
    let files = fs.readdirSync(filePath, { withFileTypes: true })

    args = args || this.config.getAll()

    this._.forEach(files, f => {
      if (f.isFile) {
        this.fs.copyTpl(this.resolvePath(filePath, f.name), this.resolvePath(destinationPath, this._renderFileName(f.name, args)), args)
      } else {
        this.copyTpl(path.resolve(filePath, f.name), path.resolve(destinationPath, f.name), args)
      }
    })
  }

  _renderFileName(fileName, args) {
    let name = fileName.replace(/\${/, "<%=").replace(/}/, ' %>')
    return ejs.render(name, args)
  }

  resolvePath(...paths) {
    return path.resolve(...paths)
  }

  end() {
    this.log(this.name + 'finished!')
  }
}